package org.xukai.common.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.LinkedList;
import java.util.List;

public class FileUtils {

	public static String getHtmlTemp(File file){
		 BufferedReader read = null;
		 ByteArrayOutputStream os = null;
		 try {
			   read = new BufferedReader(new FileReader(file));
			   os = new ByteArrayOutputStream();
			   String tempString = null;
			   while((tempString = read.readLine())!= null){
				   os.write(tempString.getBytes("utf-8"));
			   }
			   os.flush();
			   return os.toString("utf-8");
		 } catch(Exception e) {
			 e.printStackTrace();
		 }finally {
			 if (os != null) {
				 try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			 }
			 if ( read != null) {
				 try {
					read.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			 }
		 }
		 return "";
	}


    public static String readFinal(String path) {
		try {
			FileInputStream in = new FileInputStream(path);
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			byte[] buf = new byte[1024];
			int len = 0;
			while((len = in.read(buf)) != -1){
                out.write(buf,0,len);
            }
			return out.toString();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 递归删除目录下的所有文件及子目录下所有文件
	 * @param dir
	 * 将要删除的文件目录
	 */
	public static boolean deleteFolder(File dir){
		if (dir.isDirectory()) {
			// 递归删除目录中的子目录下
			File[] files = dir.listFiles();
			for(File file : files){
				deleteFolder(file);
			}
		}
		// 目录此时为空，可以删除
		return dir.delete();
	}

	/**
	 * 递归地去复制文件
	 * @param sourceFile
	 * @param file
	 * @throws IOException
     */
	public static void copy(File sourceFile, File file) throws IOException {
		while (!file.exists()){
			file.mkdir(); // 建立新的文件夹
		}
		File[] fl = sourceFile.listFiles();
		for (int i = 0; i < fl.length; i++) {
			if (fl[i].isFile()) { // 如果是文件类型就复制文件
				Path source = Paths.get(fl[i].getPath());
				Path target = Paths.get(file.getPath() + File.separator + fl[i].getName());
				Files.copy(source,target, StandardCopyOption.REPLACE_EXISTING);
			}
			if (fl[i].isDirectory()) { // 如果是文件夹类型
				File des = new File(file.getPath() + File.separator
						+ fl[i].getName());
				des.mkdir(); // 在目标文件夹中创建相同的文件夹
				copy(fl[i], des); // 递归调用方法本身
			}
		}
	}

	public static void transformEncoding(String path) throws URISyntaxException, IOException {
//		String path = "D:\\java\\IDEA-Workspace\\designpattern\\src\\main\\java\\";
		Path root = Paths.get(path);
		Files.walkFileTree(root,new FindJavaVisitor(new LinkedList<Path>()));
	}

	private static class FindJavaVisitor extends SimpleFileVisitor<Path> {
		private List<Path> result;
		public FindJavaVisitor(List<Path> result){
			this.result = result;
		}

		@Override
		public FileVisitResult visitFile(Path file, BasicFileAttributes attrs){
			String filePath = file.toFile().getAbsolutePath();
			if(filePath.endsWith("java")){
				try {
					Path path1 = Paths.get(filePath);
					byte[] bytes = Files.readAllBytes(path1);
					bytes = new String(bytes, Charset.forName("gbk")).getBytes(Charset.forName("utf-8"));
					Files.write(path1,bytes);
				} catch (IOException e) {
					e.printStackTrace();
				}
				result.add(file.getFileName());
			}
			return FileVisitResult.CONTINUE;
		}
	}

}
